package com.zz.node;

import com.zz.util.ListNodeUtil;

import java.util.Stack;

/**
 *
 * @author 张哲
 * @email a252013135@163.com
 * @date 2024/6/11 11:35
 */

/**
 * 给定一个头节点为 head 的链表用于记录一系列核心肌群训练项目编号，请查找并返回倒数第 cnt 个训练项目编号。
 * 示例 1：
 * 输入：head = [2,4,7,8], cnt = 1
 * 输出：8
 *
 * 提示：
 * 1 <= head.length <= 100
 * 0 <= head[i] <= 100
 * 1 <= cnt <= head.length
 */
public class LCR140Solution {
    public ListNode trainingPlan(ListNode head, int cnt) {
        ListNode lastNode = head;
        ListNode slowNode = head;
        for (int i = 0; i < cnt; i++) {
            lastNode = lastNode.next;
        }
        while (lastNode != null){
            lastNode = lastNode.next;
            slowNode = slowNode.next;
        }
        return slowNode;
    }

    public ListNode trainingPlanStack(ListNode head, int cnt) {
        Stack<ListNode> stack = new Stack<ListNode>();
        ListNode node = head;
        // 每一个先入栈
        while (node != null) {
            stack.push(node);
            node = node.next;
        }
        node = null;
        // 出栈
        for (int i = 0; i < cnt; i++) {
            ListNode popNode = stack.pop();
            popNode.next = node;
            node = popNode;
        }
        return node;
    }
}
